package org.chen.web.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.chen.model.domain.Users;
import org.chen.dto.UserAuthDTO;
import org.chen.enums.ApiResultEnum;
import org.chen.model.response.ApiResult;
import org.chen.model.response.ApiResultUtil;
import org.chen.model.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;

/**
 * @Author: 陈亮
 * @Date: 2019/3/24 23:08
 */
@RestController
@RequestMapping("auth")
public class AuthController {

    @Autowired
    private UsersService usersService;

    @PostMapping("login")
    public ApiResult<Users> login(@RequestBody Users users) {
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(users.getAccount(), users.getPassword());
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            if (subject.isAuthenticated()) {
                Users currentUser = (Users) subject.getPrincipal();
                Serializable sessionId = subject.getSession().getId();
                UserAuthDTO userAuthDTO = usersService.AssembleRoleAndPermissionByUser(currentUser.getId(), sessionId.toString());
                return ApiResultUtil.success(userAuthDTO);
            }
        } catch (Exception e) {
            return ApiResultUtil.error(ApiResultEnum.ACCOUNT_OR_PASSWORD_ERROR.getCode(), ApiResultEnum.ACCOUNT_OR_PASSWORD_ERROR.getMsg());
        }
        return null;
    }

    @RequestMapping("logout")
    public ApiResult logout() {
        SecurityUtils.getSubject().logout();
        return ApiResultUtil.success();
    }

    @GetMapping("unauth")
    public ApiResult unauth() {
        return ApiResultUtil.error(ApiResultEnum.NO_ACCESS_PERMISSION.getCode(), ApiResultEnum.NO_ACCESS_PERMISSION.getMsg());
    }
}
